package nd.android.am;

import java.util.HashMap;

import nd.android.am.Adapter.User;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

@Deprecated
public class UserProvider extends ContentProvider {
    private static final String TAG = "UserProvider";

    public static final String DATABASE_NAME = "account_manager.db";
    public static final int DATABASE_VERSION = 5;
    private static final String TABLE_NAME = "users";
    private static final int USERS = 1;
    private static final int USER_ID = 2;
    
    private static final UriMatcher uriMatcher;
    private static HashMap<String, String> projectionMap;
    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(Adapter.AUTHORITY, "users", USERS);
        uriMatcher.addURI(Adapter.AUTHORITY, "users/#", USER_ID);

        projectionMap = new HashMap<String, String>();
        projectionMap.put(User._ID, User._ID);
        projectionMap.put(User.NAME, User.NAME);
    }

    private DatabaseHelper dbHelper;

	@Override
	public String getType(Uri uri) {
        switch (uriMatcher.match(uri)) {
        case USERS:
            return User.CONTENT_TYPE;

        case USER_ID:
            return User.CONTENT_ITEM_TYPE;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

        qb.setTables(TABLE_NAME);
        qb.setProjectionMap(projectionMap);
        switch (uriMatcher.match(uri)) {
        case USERS:
            break;

        case USER_ID:
            qb.appendWhere(User._ID + "=" + uri.getPathSegments().get(1));
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        String orderBy = sortOrder;
        if (TextUtils.isEmpty(sortOrder)) {
            orderBy = User.DEFAULT_SORT_ORDER;
        }

        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);

        // Tell the cursor what uri to watch, so it knows when its source data changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
	}

	@Override
	public Uri insert(Uri uri, ContentValues initialValues) {
        if (uriMatcher.match(uri) != USERS) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        ContentValues values;
        if (initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
            values = new ContentValues();
        }

        // Make sure that the fields are all set
        if (values.containsKey(User.NAME) == false) {
            throw new SQLException("Failed to insert, NAME field must been setted. ");
        }

        SQLiteDatabase db = dbHelper.getWritableDatabase();
        long rowId = db.insert(TABLE_NAME, User.NAME, values);
        if (rowId > 0) {
            Uri noteUri = ContentUris.withAppendedId(User.CONTENT_URI, rowId);
            getContext().getContentResolver().notifyChange(noteUri, null);
            return noteUri;
        }

        throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int count;
        switch (uriMatcher.match(uri)) {
        case USERS:
            count = db.delete(TABLE_NAME, selection, selectionArgs);
            break;

        case USER_ID:
            String userId = uri.getPathSegments().get(1);
            count = db.delete(TABLE_NAME, User._ID + "=" + userId
                    + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int count;
        switch (uriMatcher.match(uri)) {
        case USERS:
            count = db.update(TABLE_NAME, values, selection, selectionArgs);
            break;

        case USER_ID:
            String userId = uri.getPathSegments().get(1);
            count = db.update(TABLE_NAME, values, User._ID + "=" + userId
                    + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
	}

	@Override
	public boolean onCreate() {
		dbHelper = new DatabaseHelper(getContext());
		return true;
	}

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE " + TABLE_NAME + " ("
                    + User._ID + " INTEGER PRIMARY KEY,"
                    + User.NAME + " TEXT NOT NULL"
                    + ");");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
            onCreate(db);
        }
    }
}
